/**
 * 给合并图片添加免责声明
 */
const fs = require('fs-extra');
const path = require('path');
const sharp = require('sharp');

const n = 1;

// 注意: 读取的合并户型图文件地址，更改这个文件名称看效果
const readfileName = '6.jpg';


const input = path.resolve(`./text${n}/${readfileName}`); 
const outputDir = path.resolve(`./text${n}`); // 输出地址
const output = path.resolve(outputDir, `${Date.now()}.jpg`);
const ImageController = require('./ImageController');
const imageController = new ImageController();

const TEXT = '注: 本图非专业测绘，与实际面积存在差异，请以产权证明或专业测绘为准';

(async () => {
  // 确保文件夹存在
  await fs.ensureDir(`./text${n}`);
  await fs.ensureDir(outputDir);
  
  // 创建免责声明文字buffer
  const textBuffer = await imageController.createText(TEXT, {
    fill: 'red', stroke: '',
    x: 0, y: 0, fontSize: 16, anchor: 'top'
  });

  // 读取合并户型图buffer
  let buffer = await imageController.getBuffer(input);

  // 给合并户型图bottom扩展64px (1080*0.1/2)
  buffer = await imageController.extend(buffer, {
    bottom: 1080 * 0.1 / 2
  });

  // 读取扩展后的图片宽高
  const { width, height } = await imageController.getMetadata(buffer);

  // 对扩展后的图片拼接免责声明文字
  buffer = await sharp(buffer).composite([{
    input: textBuffer,
    top: Math.ceil(height - 1080 * 0.1 / 4),
    left: 0
  }]).jpeg().toBuffer()

  // 重新将整体图片resize到1440*1080
  buffer = await imageController.resize(buffer, {
    width: 1440,
    height: 1080
  })

  // 输出图片
  await imageController.toFile(buffer, output);

  console.log('完成');
})();